package com.tz.online.cart;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tz.online.book.service.IBookService;
import com.tz.online.entity.Book;
import com.tz.online.entity.Cart;
import com.tz.online.entity.OrderItem;
import com.tz.online.util.BeanFactory;

/**
 * 接收添加购物车请求
 * @author Administrator
 *
 */
@WebServlet(name="addCart",urlPatterns="/cart/addCart")
public class AddCartAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6783205952016838715L;
	IBookService bs = (IBookService) BeanFactory.getBean("bookService");
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		try {
			
			String bid = req.getParameter("bookId");
			
			Book book = bs.queryBookById(bid);
			OrderItem item = new OrderItem();
			item.setAllPrice(book.getPrice());
			item.setCount(1);
			item.setBook(book);
			
			Cart cart = (Cart) req.getSession().getAttribute("cart");
			if(cart == null){
				cart = new Cart();
			}
			
			cart.addCart(item);
			
			req.getSession().setAttribute("cart", cart);
			
			out.print("1:"+cart.getAllcount()+":"+cart.getAllPrice());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.print("0");
			e.printStackTrace();
		}
		
		
		/*
		try {
			//接收ID
			Book book = null;//根据ID查询对象
			
			//利用商品对象封装一个订单明细对象
			OrderItem item = null;
			
			//获得购物车
			Cart  cart = req.getSession().getAttribute("cart");
			
			if(cart == null){
				
				cart = new Cart();
			}
			
			//把订单明细添加到购物车
			cart.addCart(item);
			
			req.getSession().setAttribute("cart", cart);
			
			out.print("1:5");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.ptint("0");
			e.printStackTrace();
		}*/
	}
}
